package com.dst.smart.music;

import com.dst.smart.app.MainActivity;
import com.dst.smart.json.SongUitils;
import com.dst.smart.player.InsType;
import com.dst.smart.player.PlayController;
import com.dst.smart.player.VolumeManager;
import com.dst.smart.player.entity.SongPlayInfo;
import com.dst.smart.service.SendCMD;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.LinearLayout;

import java.util.List;

public class MusicPlayMedia extends LinearLayout implements
		OnCompletionListener {
	static Context context;
	private static MediaPlayer mediaPlayer;
	public static int playState = 0;
	private String FileName;
	private int Duration;
	private int state;
	public static MusicPlayMedia instansMedia;
	private static int currentVolume = 50;
	private boolean prebFlag =false;
	VolControlThread mVolControlThread;
	private static int tempVol=50;

	enum INSTYPE {
		NEXT, PAST, REPLAY, REPEAT, PAUSE, VOLMAX, VOLMID, VOLMIN, VOLMINUS, VOLPLUS, INSTYPE_REPLAYANSWER,VOLUME_SELECT
	};
	// 要播放的歌曲信息
	private List<SongPlayInfo> mSongInfoList;

	// 当前播放歌曲信息
	private SongPlayInfo mSongInfo;

	// 播放的第几个歌曲
	private int playIndex = 0;

	// 歌单歌曲总数
	private int playCount = 0;

	public static MusicPlayMedia getInstansMedia() {
		if (instansMedia == null) {
			instansMedia = new MusicPlayMedia(MainActivity.activity, "");
		}
		return instansMedia;
	}
	public void setVol(boolean isVol){
		if(mVolControlThread==null) {
			mVolControlThread = new VolControlThread();
			mVolControlThread.start();
		}

		mVolControlThread.start(isVol);
	}
	public String getFileName() {
		return FileName;
	}

	public void playControllerURLList(String uuid, List<SongPlayInfo> newsList) {
		PlayController.getInstance(context).playURLList(uuid, newsList);
	}
	public void playControllerText(String uuid, String text, boolean readDigit, String emot,
						 Runnable runnable){
		PlayController.getInstance(context).playText(uuid, text, readDigit, emot, runnable);
	}

	public void setFileName(int state, String fileName,int isPlayMusic ) {
		if(isPlayMusic<2) {
			this.state = state;
			FileName = fileName;
		}else{
			if(MainActivity.musicPlaySt){
				stop();
			}
			MainActivity.playSound(5,fileName);
		}
		MainActivity.isPlayMusic=isPlayMusic;
	}
	public void playURLList(List<SongPlayInfo> songList) {
		stop();
		//PlayController.getInstance(context).stopPlayControl();
		//PlayController.getInstance(context).pauseMusic();
		PlayController.getInstance(context).musicRecover=false;
		if(MainActivity.musicTTsSt ) {
			PlayController.getInstance(context).stopTTS();
		}
		MainActivity.musiconlyonce=false;
		playIndex=0;
		mSongInfoList = songList;
		playCount = (mSongInfoList!=null)?mSongInfoList.size():0;
	}

	// 上一首
	public void previous() {
        if(MainActivity.isPlayMusic<2) {
		    if (0 == playIndex) {
				MainActivity.playSound(5, "当前是第一首");
		    } else {
			    playIndex--;
				playState(false,"previous");
			    playItem();
		    }
        }else{
        	PlayController.getInstance(context).previous();
        }
	}
	// 下一首
	public void next() {
        if(MainActivity.isPlayMusic<2) {
			playState(false,"next");
			if(MainActivity.playMode==0) {
				playIndex += 1;
				if(playIndex >= playCount){
					if(playCount>0) {
						playIndex=0;
						String endPlayText = "内容播报完毕";
						if (MainActivity.isPlayMusic == 0) {
							endPlayText = "当前歌单没有更多歌曲，播放停止";
						}
						MainActivity.playSound(5, endPlayText);
						Log.e("text", "MusicPlayMedia next " + endPlayText);
					}
					return;
				}
			}else if(MainActivity.playMode==2) {
				playIndex += 1;
				if (playIndex >= playCount) {
					if (playCount > 0) {
						playIndex = 0;
					}else{
						return;
					}
				}
			}
			playItem();
        }else{
         	PlayController.getInstance(context).next();
        }
	}
	public void playNumber(int number) {
		if(MainActivity.isPlayMusic<2) {
            if (null != mSongInfoList && mSongInfoList.size() >0) {
                if ((number > 0) && (number <= playCount)) {
					if (playIndex != (number - 1)){
						playIndex = number - 1;
						playState(false, "playNumber");
						playItem();
					}else{
						MainActivity.playSound(5, "当前正在播放第" + number + "首");
					}
                }
            }
		}
	}
	public void playLast() {
		if(MainActivity.isPlayMusic<2) {
			if (null != mSongInfoList && mSongInfoList.size() >0) {
				if(playIndex!=(playCount- 1)) {
					playIndex = playCount - 1;
					playState(false, "playLast");
					playItem();
				}else{
					MainActivity.playSound(5, "当前已經是最後一首");
				}
			}
		}
	}
	public void playItem() {

		if (null != mSongInfoList && mSongInfoList.size() >0) {
			final String playUrl;
			if(MainActivity.isPlayMusic==0) {
				// 获得歌曲的信息
				mSongInfo = mSongInfoList.get(playIndex);
				String songName = mSongInfo.getSongName();
				//String singerName = mSongInfo.getSingerName();
				playUrl = mSongInfo.getPlayUrl();
				//musicInfo = "请欣赏." + singerName + songName;
				if (TextUtils.isEmpty(playUrl)) {
					//MainActivity.playSound(4, "歌曲信息有误，换一首吧");
					//playState(false,"playItem");
					Log.e("text","playItem 歌曲信息有误，换一首吧");
					next();
					return;
				}
				//String answerText = mSongInfo.getAnswerText();
				//String ttsText = "第" + (playIndex+1) + "首" + singerName + "的" + songName;
			}else{
				playUrl=mSongInfoList.get(playIndex).getPlayUrl();
				if (TextUtils.isEmpty(playUrl)) {
					playState(false,"playItem");
					return;
				}
			}
			setFileName(0,playUrl,MainActivity.isPlayMusic);
			play();
		}else{
			Log.e("text","MusicPlayMedia playItem : null != mSongInfoList && mSongInfoList.size() >0");
		}
	}
	public int getDuration() {
		return Duration;
	}

	/*
	 * StringUtils .getCurrentTime(current)
	 */
	public int time() {
		try {
			if (mediaPlayer.isPlaying()) {
				return (int) mediaPlayer.getCurrentPosition() / 1000;
			}
		} catch (Exception e) {
			return -1;
		}
		return -1;
	}

	public void setDuration(int duration) {
		Duration = duration;
	}

	private int musicAction;

	private String playerVolume = "0.5";

	public String getPlayerVolume() {
		return playerVolume;
	}

	public void setPlayerVolume(String playerVolume) {
		this.playerVolume = playerVolume;
	}

	public int getMusicAction() {
		return musicAction;
	}

	public void setMusicAction(int musicAction) {
		this.musicAction = musicAction;
	}

	public MusicPlayMedia(Context context, String musicName) {

		super(context);
		this.context = context;
		instansMedia = this;
		this.FileName = musicName;
		init();
	}

	public void init() {
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setVolume(1.0f, 1.0f);
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

			@Override
			public void onPrepared(MediaPlayer mp) {
				try {
					if(!PlayController.getInstance(context).musicRecover) {
						mp.start();
						playState(true, "setOnPreparedListener");
						if (null != mSongInfoList && mSongInfoList.size() > 0) {
							if ((MainActivity.isPlayMusic == 0)&&(MainActivity.playMode!=1)) {
								mSongInfo = mSongInfoList.get(playIndex);
								MainActivity.playSound(5, "请欣赏." + mSongInfo.getSingerName() + mSongInfo.getSongName());
								Log.e("text", (playIndex + 1) + " setOnPreparedListener " + "请欣赏." + mSongInfo.getSingerName() + mSongInfo.getSongName());
							}
						}
					}
				} catch (Exception e) {
					System.out.println(e.toString());
				}
			}
		});
		mediaPlayer.setOnErrorListener(new OnErrorListener() {

			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				// TODO Auto-generated method stub
				try {
					if(MainActivity.isPlayMusic<2) {
						//if(MainActivity.musicPlaySt) {
						//MainActivity.playSound(4, "内容开小差，换首别的吧");
						next();
						Log.e("text", "setOnErrorListener");
						//}
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				return true;
			}
		});
		//mediaPlayer.setOnBufferingUpdateListener();
		setVolume(currentVolume);
	}

	public void play() {
		try {
			mediaPlayer.reset();
			if (state == 1) {
				mediaPlayer.setDataSource(FileName);
			} else {
				mediaPlayer.setDataSource(context, Uri.parse(FileName));
			}
			mediaPlayer.prepareAsync();
			// mediaPlayer.prepare();
			playState(true,"play");
		}catch (Exception e){
		}
	}

	public void continuePlay() {
		if(MainActivity.isPlayMusic<2) {
			mediaPlayer.start();
			playState(true,"continuePlay");
		}else{
			//PlayController.getInstance(context).resumeMusic();
			PlayController.getInstance(context).resumeTTS();
		}
	}

	public void pause() {
		if(MainActivity.isPlayMusic<2) {
			mediaPlayer.pause();
			playState(false,"pause");
		}else {
			if(mediaPlayer!=null&&mediaPlayer.isPlaying()) {
				mediaPlayer.stop();
			}
			PlayController.getInstance(context).pauseMusic();
			//PlayController.getInstance(context).stopTTS();
		}
	}

	public void stop() {
		if(MainActivity.isPlayMusic<2) {
			if (mediaPlayer != null) {
				try {
					mediaPlayer.stop();
					mediaPlayer.reset();
					mSongInfoList = null;
					playState(false,"stop");
				} catch (Exception e) {
				}
			}
		}
	}

	public void setVolume() {
		try {
			mediaPlayer.setVolume(
					Float.parseFloat(getPlayerVolume()),
					Float.parseFloat(getPlayerVolume()));
		} catch (Exception e) {
		}
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub
		playState(false,"onCompletion");
		try {
			if(MainActivity.musiconlyonce){
				MainActivity.musiconlyonce=false;
			}else {
				next();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void setVolume(int value) {

		currentVolume=value;
		tempVol=value;
		if (instansMedia != null && mediaPlayer != null) {
			float leftVolume = (float) value / 100;
			mediaPlayer.setVolume(leftVolume, leftVolume);
		}
		PlayController.getInstance(context).setVolume(((value*15)/100)+1);
	}
	public static int getVolume() {
	return currentVolume;
	}


	public static void setDownVolume() {
		//if(MainActivity.isPlayMusic<2) {
//			if (instansMedia != null && mediaPlayer != null) {
//				if (currentVolume >= 20) {
//					currentVolume -= 10;
//					float leftVolume = (float) currentVolume / 100;
//					mediaPlayer.setVolume(leftVolume, leftVolume);
//				} else {
//					MainActivity.playSound(0, "最小音量");
//				}
//			}
		//}else{
			PlayController.getInstance(context).onMusicCommand("", InsType.VOLMINUS);
		//}
		currentVolume=(PlayController.getInstance(context).getCurrentVolum()*100)/15;
		if(currentVolume==20){
			MainActivity.playSound(5, "已是最小音量");
		}
	}

	public static void setUpVolume() {
		//if(MainActivity.isPlayMusic<2) {
//			if (instansMedia != null && mediaPlayer != null) {
//
//				if (currentVolume < 100) {
//					currentVolume += 10;
//					float leftVolume = (float) currentVolume / 100;
//					mediaPlayer.setVolume(leftVolume, leftVolume);
//				} else {
//					MainActivity.playSound(0, "最大音量");
//				}
//			}
		//}else{
			PlayController.getInstance(context).onMusicCommand("", InsType.VOLPLUS);
		//}

		currentVolume=(PlayController.getInstance(context).getCurrentVolum()*100)/15;

		if(currentVolume==100){
			MainActivity.playSound(5, "已是最大音量");
		}
	}

	public boolean isPlaying() {
		if (mediaPlayer == null || instansMedia == null) {
			return false;
		}
		return mediaPlayer.isPlaying();
	}

	private void playState(boolean bFlag,String act) {
		if(prebFlag!=bFlag){
			prebFlag=bFlag;
			MainActivity.musicPlaySt = bFlag;
			SendCMD cmdsend = SendCMD.getInstance();
			cmdsend.sendSubCmd(200, bFlag ? "1" : "0", null,0);
		}
		Log.e("text","MusicPlayMedia "+ playCount+":"+(playIndex+1) + (bFlag ? " 1 " : " 0 ") + act);
	}
	public int addSong(){
		int result=0;
		if(mSongInfoList!=null&&mSongInfoList.size()>0) {
			result=	SongUitils.add(mSongInfoList.get(playIndex));
		}
		return result;
	}
	public  void delete(){
		if(mSongInfoList!=null&&mSongInfoList.size()>0) {
			SongUitils.delete(mSongInfoList.get(playIndex));
		}
	}
	public static void deleteAll(){
		SongUitils.deleteAll();
	}


	private class VolControlThread extends Thread{

		boolean isRunning = false;
		boolean isVol=false;
		public boolean isRunning() {
			return isRunning;
		}

		public void start(boolean _isVol){
			isVol=_isVol;
			isRunning = true;
		}

		@Override
		public void run() {
			super.run();
			while(true){
				if(isRunning){
					if(isVol){
						if(tempVol<getVolume()){
							float leftVolume = (float) tempVol / 100;
							mediaPlayer.setVolume(leftVolume,leftVolume);
							tempVol+=5;
						}else{
							isRunning = false;
						}
					}else{
						if(tempVol>=10){
							float leftVolume = (float) tempVol / 100;
							mediaPlayer.setVolume(leftVolume,leftVolume);
							tempVol-=5;
						}else{
							isRunning = false;
						}
					}
				}
				try {
					sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
